
import {GetUrlBase, getHttpObj, encode, ClientTypes} from "@/views/office/common/common"
import {fileInfoEnum} from "@/components/WpsOffice/common/common";
let bFinished = true;


/**
 * 通过该接口给服务器发请求
 * @param {*} options       参数对象，具体包含的参数如下：
 * @param {*} url           网页路径，传输地址
 * @param {*} type          传输类型，POST / GET / PUT
 * @param {*} sendData      传输的数据
 * @param {*} callback      回调函数
 * @param {*} tryCount      请求失败后的尝试次数
 * @param {*} bPop          是否弹出浏览器提示对话框
 * @param {*} timeout       请求等待响应的时间，超过时间请求实效
 * @param {*} concurrent    请求是否同步发送
 * @param {*} client        wpsclient对象
 * @returns NULL
 */
let startWps = (options)=>{
  console.log('startWps(options)',options)
  if (!bFinished && !options.concurrent) {
    if (options.callback)
      options.callback({
        status: 1,
        message: "上一次请求没有完成"
      });
    return;
  }
  bFinished = false;

  let startWpsInnder = (tryCount)=>{
    if (tryCount <= 0) {
      if (bFinished)
        return;
      bFinished = true;
      if (options.callback)
        options.callback({
          status: 2,
          message: "请允许浏览器打开WPS Office"
        });
      return;
    }
    let xmlReq = getHttpObj();
    //WPS客户端提供的接收参数的本地服务，HTTP服务端口为58890，HTTPS服务端口为58891
    //这俩配置，取一即可，不可同时启用
    xmlReq.open('POST', options.url);
    xmlReq.onload = function (res) {
      bFinished = true;
      if (initCloudsvr == true) {
        initCloudsvr = false;
      }
      if (options.callback) {
        if(res.target.response == "{\"data\": \"Failed to send message to WPS.\"}"){
          options.callback({
            status: 1,
            message:  res.target.response
          });
        }else if(res.target.response!= null && res.target.response.indexOf("No Plugin named:") != -1){
          alert("请启用WPS插件")
        }
        else {
          options.callback({
            status: 0,
            response:  res.target.response
          });
        }
      }
    }
    xmlReq.ontimeout = xmlReq.onerror = function (res) {
      xmlReq.bTimeout = true;
      if (tryCount == options.tryCount && options.bPop && initCloudsvr == false) { //打开wps并传参
        if (os.platform() != 'darwin') {
          InitWpsCloudSvr();
        }
      }
      setTimeout(function () {
        startWpsInnder(tryCount - 1)
      }, 1000);
    }
    xmlReq.timeout = options.timeout;
    xmlReq.send(options.sendData)
  }
  startWpsInnder(options.tryCount);
  return;
}




/**
 * 支持浏览器触发，WPS有返回值的启动
 *
 * @param {*} clientType	组件类型
 * @param {*} name			WPS加载项名称
 * @param {*} func			WPS加载项入口方法
 * @param {*} param			参数：包括WPS加载项内部定义的方法，参数等
 * @param {*} callback		回调函数
 * @param {*} tryCount		重试次数
 * @param {*} bPop			是否弹出浏览器提示对话框
 */
let exId = 0;
let WpsStartWrapExInner = (options) => {
  let infocontent = options.param.param;
  let time = new Date();
  let cmdId = "js" + time.getTime() + "_" + exId;
  if (!options.wpsclient || options.wpsclient.single) {
    infocontent = JSON.stringify(options.param.param);
    let rspUrl = options.urlBase + "/transferEcho/runParams";
    let funcEx = "let res = " + options.func;
    let cbCode = "let xhr = new XMLHttpRequest();xhr.open('POST', '" + rspUrl + "');xhr.send(JSON.stringify({id: '" + cmdId + "', response: res}));" //res 为func执行返回值
    let infoEx = infocontent + ");" + cbCode + "void(0";
    options.func = funcEx;
    infocontent = infoEx;
  }
  let startInfo = {
    "name": options.name,
    "function": options.func,
    "info": infocontent,
    "showToFront": options.param.showToFront,
    "jsPluginsXml": options.param.jsPluginsXml,
  };

  console.log('startInfo',startInfo)
  let strData = JSON.stringify(startInfo);

  let baseData = encode(strData);
  let wrapper;
  let url ;
  if (!options.wpsclient|| options.wpsclient.single) {
    url = options.urlBase + "/transfer/runParams";
    let data = "ksowebstartup" + options.clientType + "://" + baseData;
    wrapper = {
      id: cmdId,
      app: options.clientType,
      data: data,
      mode: options.silentMode ? "true" : "false",
    };
  }
  else {
    url = options.urlBase + "/transferEx/runParams";
    wrapper = {
      id: options.wpsclient.clientId,
      app: options.clientType,
      data: baseData,
      mode: options.wpsclient.silentMode ? "true" : "false",
    };
  }
  console.log('wrapper',wrapper)
  wrapper = JSON.stringify(wrapper);
  startWps({
    url: url,
    sendData: wrapper,
    callback: options.callback,
    tryCount: options.tryCount,
    bPop: options.bPop,
    timeout: 0,
    concurrent: options.concurrent,
    client: options.wpsclient
  });
}

let serverVersion = "wait"
let cloudSvrStart = true;
let initCloudsvr = false;
/**
 * 获取服务端版本号的接口
 * @param {*} options       参数对象，详情见下：
 * @param {*} clientType    加载项类型， wps / wpp / et
 * @param {*} name          加载项名称
 * @param {*} func          客户端加载项要执行的方法
 * @param {*} param         客户端家乡执行方法的参数
 * @param {*} urlBase       网页路径前缀
 * @param {*} callback      回调函数
 * @param {*} wpsclient     wpsclient对象
 * @param {*} concurrent    请求是否同步发送
 */
let WpsStartWrapVersionInner = (options) => {
  if (serverVersion == "wait") {
    if (cloudSvrStart == false) {
      InitWpsCloudSvr();
      initCloudsvr = true;
    }
    startWps({
      url: options.urlBase + '/version',
      sendData: JSON.stringify({  }),
      callback: function (res) {
        if (res.status !== 0) {
          options.callback(res)
          return;
        }
        serverVersion = res.response;
        cloudSvrStart = true;
        options.tryCount = 1
        options.bPop = false
          WpsStartWrapExInner(options);
      },
      tryCount: 4,
      bPop: true,
      timeout: 5000,
      concurrent: options.concurrent
    });
  } else {
    options.tryCount = 4
    options.bPop = true
      WpsStartWrapExInner(options);
  }
}


/**
 * 自定义协议启动服务端
 */
let InitWpsCloudSvr = () => {
    location.href = "ksoWPSCloudSvr://start=RelayHttpServer"//是否启动wps弹框
}


let RegWebNotifyMap = { wps: {}, wpp: {}, et: {} }
let g_businessId = Number(Math.random().toString().substr(3, 5) + Date.parse(new Date())).toString(36);

let isRunTimeoutAskItem = false
// export const stopRunTimeoutAskItem = function (ask,time) {
//   isRunTimeoutAskItem = false;
// }
export const timeoutAskItem = function (ask,time,clientTypeTemp,nameTemp,routeTemp,officeIDTemp) {
  // if(isRunTimeoutAskItem){
      setTimeout(ask, time,clientTypeTemp,nameTemp,routeTemp,officeIDTemp);
  // }else {
  // }
}

/**
 * 注册一个前端页面接收WPS传来消息的方法
 * @param {*} clientType wps | et | wpp
 * @param {*} name WPS加载项的名称
 * @param route
 * @param officeID
 * @param {*} callback 回调函数
 */
export const sdkRegWebNotify = (clientType, name, route, officeID, callback) => {
  console.log(clientType, name, route, officeID, callback,'clientType, name, route, officeID, callback')
  if (clientType != "wps" && clientType != "wpp" && clientType != "et")
    return;
  // if (route == undefined)
  //   return;
  if (officeID == undefined)
    return;
  let paramStr = {}
  if (typeof callback != 'function')
    return
  if (RegWebNotifyMap[clientType][name] == null) {
    RegWebNotifyMap[clientType][name] = {};
  }
  // if (RegWebNotifyMap[clientType][name][route] == null) {
  //   RegWebNotifyMap[clientType][name][route] = {};
  // }
// Object.keys(json).length
  // RegWebNotifyMap[clientType][name][route][officeID] = callback ;
  RegWebNotifyMap[clientType][name][officeID] = callback ;

  if(Object.keys(RegWebNotifyMap[clientType][name]).length >1){
    return;
  }

  let RegWebNotifyID = new Date().valueOf() + ''
  paramStr = {
    id: RegWebNotifyID,
    name: name,
    type: clientType,
  }
    paramStr.businessId = g_businessId

  // isRunTimeoutAskItem = true;

  let askItem = function (clientTypeTemp,nameTemp,routeTemp,officeIDTemp) {
    console.log('nameTemp,routeTemp,officeIDTemp',nameTemp,routeTemp,officeIDTemp)
    // if(Object.keys(RegWebNotifyMap[clientTypeTemp][nameTemp][routeTemp]).length == 0){
    if(Object.keys(RegWebNotifyMap[clientType][name]).length == 0){
      return;
    }
    let xhr = getHttpObj()
    xhr.onload = function (e) {
      if (xhr.responseText == "WPSInnerMessage_quit") {
        return;
      }
      try {
        let resText = JSON.parse(xhr.responseText);
        if (typeof resText == 'object') {
          paramStr.messageId = resText.msgId;
        }
        // if (wpsclient) {
        //   if (typeof resText.data == 'object')  // 如果发的数据是字符串化后的json对象，这里的resText.data就是一个json对象，可以输出自己想要的json数据
        //     wpsclient.OnRegWebNotify(resText.data.data)
        //   else
        //     wpsclient.OnRegWebNotify(resText.data)
        // } else {
        //   let func = RegWebNotifyMap[clientTypeTemp][nameTemp][routeTemp][officeIDTemp]
          let func = RegWebNotifyMap[clientTypeTemp][nameTemp][resText.data[fileInfoEnum.officeId]]
          if(typeof func == "function"){
            func(clientTypeTemp, nameTemp,resText.data[fileInfoEnum.routeId],resText.data[fileInfoEnum.officeId], resText.data)
          }
        // }
      }
      catch (e) {
        // 这里做一个容错，即使json解析失败，也要把msgId提取出来，发回给服务端，避免消息清不掉一直重复发送
        // 同时把data也取出来，但是格式无法保证
        // let str = xhr.responseText
        // let idx1 = str.indexOf(":")
        // let idx2 = str.indexOf(",")
        // paramStr.messageId = parseInt(str.substring(idx1 + 1, idx2))
        // let idx3 = str.indexOf("\"data\"")
        // let idx4 = str.indexOf("}")
        // let data = str.substring(idx3, idx4)
        // if (wpsclient) {
        //   if (data)
        //     wpsclient.OnRegWebNotify(data)
        //   else
        //     wpsclient.OnRegWebNotify(xhr.responseText)
        // } else {
        //   let func = RegWebNotifyMap[clientTypeTemp][nameTemp][routeTemp][officeIDTemp]
        //   let func = RegWebNotifyMap[clientTypeTemp][data[fileInfoEnum.routeId]][data[fileInfoEnum.officeId]]
        //   if(typeof func != "function"){
        //     return;
        //   }
        //   if (data)
        //     func(clientTypeTemp, nameTemp,data[fileInfoEnum.routeId],data[fileInfoEnum.officeId], data)
        //   else
            console.error("WPS消息处理失败",xhr.responseText)
        // }
      }
      timeoutAskItem(askItem, 300,clientTypeTemp,nameTemp,routeTemp,officeIDTemp)
    }
    xhr.onerror = function (e) {
        timeoutAskItem(askItem, 1000,clientTypeTemp,nameTemp,routeTemp,officeIDTemp)
    }
    xhr.ontimeout = function (e) {
        timeoutAskItem(askItem, 300,clientTypeTemp,nameTemp,routeTemp,officeIDTemp)
    }
    xhr.open('POST', GetUrlBase() + '/askwebnotify', true)
    xhr.timeout = 2000;
    xhr.send(JSON.stringify(paramStr));
  }
  timeoutAskItem(askItem, 2000,clientType,name,route,officeID)
}



/**
 * 获取服务端版本号的接口，这里主要是初始化一些参数
 * @param {*} clientType    加载项类型， wps / wpp / et
 * @param {*} name          加载项名称
 * @param {*} func          客户端加载项要执行的方法
 * @param {*} param         客户端家乡执行方法的参数
 * @param {*} callback      回调函数
 * @param {*} showToFront   设置客户端是否显示到前面
 * @param {*} jsPluginsXml  设置加载项路径
 * @param {*} silentMode    静默启动WPS
 */
export const sdkWpsStartWrapVersion = (clientType, name, func, param, callback, showToFront, silentMode) => {
  let paramEx = {
    jsPluginsXml: "",
    showToFront: typeof (showToFront) == 'boolean' ? showToFront : true,
    param: (typeof (param) == 'object' ? param : JSON.parse(param))
  }
  let options = {
    clientType: clientType,
    name: name,
    func: func,
    param: paramEx,
    urlBase: GetUrlBase(),
    callback: callback,
    wpsclient: undefined,
    concurrent: true,
    silentMode:silentMode
  }
  WpsStartWrapVersionInner(options);
}

/**
 * 取消注册方法
 */
export const sdkCancelRegWebNotify = (clientType, name,officeId)=>{
  console.log(clientType, name,officeId,'clientType, name,officeId')
  if (clientType != "wps" && clientType != "wpp" && clientType != "et")
    return;
  if (officeId == undefined)
    return;
  if(RegWebNotifyMap[clientType][name] != undefined){
    if(RegWebNotifyMap[clientType][name][officeId] != undefined) {
      delete RegWebNotifyMap[clientType][name][officeId];
    }
  }
  // 判断是否还有剩余，不存在的话，取消监听
  // if(
  //     (RegWebNotifyMap[clientType][ClientTypes.wps] == undefined || (RegWebNotifyMap[clientType][ClientTypes.wps] != undefined && RegWebNotifyMap[clientType][ClientTypes.wps].length == 0))
  //     && (RegWebNotifyMap[clientType][ClientTypes.et] == undefined || (RegWebNotifyMap[clientType][ClientTypes.et] != undefined && RegWebNotifyMap[clientType][ClientTypes.et].length == 0))
  // ){
  //   isRunTimeoutAskItem = false ;
  // }
}


/**
 * 初始化sdk，用来减少在服务进程启动时自定义协议弹框出现的次数
 */
let InitSdk = () => {
  let url = GetUrlBase() + "/version";
  startWps({
    url: url,
    callback: function (res) {
      if (res.status !== 0) {
        cloudSvrStart = false;
        return;
      }
    },
    tryCount: 1,
    bPop: false,
    timeout: 1000
  });
}
InitSdk();


/**
 * 当前客户端是否在运行，使用WpsInvoke.IsClientRunning()进行调用
 * @param {string} clientType       加载项类型
 * @param {function} [callback]      回调函数，"Client is running." 客户端正在运行
 *                                   "Client is not running." 客户端没有运行
 */
export const IsClientRunning = (clientType, callback, wpsclient) => {
  let url = GetUrlBase() + "/isRunning";
  let wrapper = {
    id: wpsclient == undefined ? undefined : wpsclient.clientId,
    app: clientType,
  }
  wrapper = JSON.stringify(wrapper);
  startWps({
    url: url,
    sendData: wrapper,
    callback: callback,
    tryCount: 1,
    bPop: false,
    timeout: 2000,
    concurrent: true,
    client: wpsclient
  });
}

// //从外部浏览器远程调用 WPS 加载项中的方法
// export const WpsInvoke = {
//   InvokeAsHttp: WpsStartWrapVersion,
//   InvokeAsHttps: WpsStartWrapVersion,
//   RegWebNotify: RegWebNotify,
//   CancelRegWebNotify: CancelRegWebNotify,
//   ClientType: ClientTypes,
//   CreateXHR: getHttpObj,
//   IsClientRunning: IsClientRunning
// }

